<template>
  <el-card class="edit-profile-card">
    <div slot="header">
      <h2>编辑个人资料</h2>
    </div>
    <div class="fun-btn">
      <!-- 返回按钮 -->
      <el-button
        type="primary"
        @click="$router.push('/admin/users')"
        icon="el-icon-back"
      >
        返回
      </el-button>
    </div>
    <div style="height: 50px"></div>
    <el-form
      ref="profileForm"
      :model="profileForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="profileForm.username" disabled></el-input>
        <div class="el-form-item__error">用户名不可修改</div>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="profileForm.email"></el-input>
      </el-form-item>
      <el-form-item label="个人简介" prop="bio">
        <el-input
          type="textarea"
          v-model="profileForm.bio"
          placeholder="请输入个人简介"
          :rows="5"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" icon="el-icon-check"
          >保存</el-button
        >
        <el-button @click="handleCancel" icon="el-icon-close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        profileForm: {
          username: "",
          email: "",
          bio: "",
        },
        userId: null,
        rules: {
          email: [
            { required: true, message: "请输入邮箱", trigger: "blur" },
            {
              type: "email",
              message: "请输入正确的邮箱格式",
              trigger: ["blur", "change"],
            },
          ],
          bio: [
            { max: 500, message: "个人简介不能超过500个字符", trigger: "blur" },
          ],
        },
      };
    },
    created() {
      this.userId = this.$route.params.id;
      // console.log("created,", this.$route);
      this.loadUserProfile();
    },
    methods: {
      async loadUserProfile() {
        try {
          let user = await this.$axios.get(`/user/${this.userId}`);
          user = user.data;
          this.profileForm = {
            username: user.username,
            email: user.email,
            bio: user.bio || "",
          };
        } catch (error) {
          this.$message.error("加载个人资料失败");
          console.error(error);
        }
      },
      async handleSubmit() {
        this.$refs.profileForm.validate(async (valid) => {
          if (valid) {
            try {
              // eslint-disable-next-line no-unused-vars
              const { username: _username, ...updateData } = this.profileForm;
              await this.$axios.put(`/user/${this.userId}`, updateData);
              // eslint-disable-next-line no-unused-vars
              this.$store.dispatch("setUser", {
                userInfo: { ...this.$store.getters.user, ...updateData },
              });
              this.$message.success("个人资料更新成功");
              // 提取 $route 中queryString的参数
              if (this.$route.query?.type === "profile") {
                this.$router.push(`/user/${this.userId}`);
                return;
              }
              this.$router.push(`/user/${this.userId}/detail`);
            } catch (error) {
              this.$message.error("更新失败");
              console.error(error);
            }
          } else {
            return false;
          }
        });
      },
      handleCancel() {
        this.$router.go(-1);
      },
    },
  };
</script>

<style scoped>
  .edit-profile-card {
    max-width: 600px;
    margin: 20px auto;
  }
</style>
